const { <%= modelName %> } = require("../../models");
const { Op } = require("sequelize");
const { NotFoundError } = require("../../utils/errors");
const { paging } = require("../../utils/utils");

/**
* 获取分页列表
* @param req
* @returns {Promise<{rows: Model[], count: number}>}
*/
exports.list = async (req) => {
try {
// 获取分页参数
const { query, currentPage, pageSize, offset } = paging(req);
const condition = {
order: [
["id", "ASC"]
],
limit: pageSize,
offset: offset,
};
//查询条件
getCondition(condition, query);
// 分页查询
const { rows, count } = await <%= modelName %>.findAndCountAll(condition);
return { rows, count, currentPage, pageSize };
} catch (error) {
throw new Error(error);
}
};

/**
* 获取所有<%= title %>
* @param req
* @returns {Promise< Model[] >}
*/
exports.all = async (req) => {
try {
const condition = {
order: [
["id", "ASC"]
]
};
//查询条件
getCondition(condition, req.query);
return await <%= modelName %>.findAll(condition);
} catch (error) {
throw new Error(error);
}
};

/**
* 获取<%= title %>详情
* @param id
* @returns {Promise< Model<*, TModelAttributes>>}
*/
exports.details = async (id) => {
try {
return await this.getById(id);
} catch (error) {
throw new Error(error);
}
};

/**
* 创建<%= title %>
* @param body
* @returns {Promise< Model< any, TModelAttributes>>}
*/
exports.create = async (body) => {
try {
return await <%= modelName %>.create(body);
} catch (error) {
throw new Error(error);
}
};

/**
* 删除<%= title %>
* @param id
* @returns {Promise< void>}
*/
exports.del = async (id) => {
try {
const <%= modelName.toLowerCase() %> = await this.getById(id);
await <%= modelName.toLowerCase() %>.destroy();
} catch (error) {
throw new Error(error);
}
};

/**
* 更新<%= title %>
* @param id
* @param body
* @returns {Promise< Model<*, TModelAttributes>>}
*/
exports.update = async (id, body) => {
try {
const <%= modelName.toLowerCase() %> = await this.getById(id);
await <%= modelName.toLowerCase() %>.update(body);
return <%= modelName.toLowerCase() %>;
} catch (error) {
throw new Error(error);
}
};

/**
* 根据id获取<%= title %>
* @param id
* @returns {Promise< Model< any, TModelAttributes>>}
*/
exports.getById = async (id) => {
// 获取当前<%= title %>
const <%= modelName.toLowerCase() %> = await <%= modelName %>.findByPk(id);
if (!<%= modelName.toLowerCase() %>) {
throw new NotFoundError(`ID: ${id} not found`);
}
return <%= modelName.toLowerCase() %>;
};

/**
* 获取条件
* @param condition
* @param query
*/
function getCondition(condition, query) {
<% for(var i = 0; i < fields.length; i++) { %>
    // <%= fields[i].title %>
    if (query.<%= fields[i].name %>) {
    condition.where = {
    <%= fields[i].name %>: {
    [Op.like]: `%${query.<%= fields[i].name %>}%`,
    },
    };
    }
<% } %>
}
